<template>
    <div class="page-root">
        <h2 class="main-title">客户外出登记审核</h2>
        <!-- 查询表单 -->
        <el-form :inline="true" :model="searchForm" class="search-bar">
            <el-form-item label="客户姓名">
                <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
            </el-form-item>
            <el-form-item label="预计返回日期">
                <el-date-picker v-model="searchForm.expectedReturnTime" type="date" value-format="YYYY-MM-DD" clearable />
            </el-form-item>
            <el-form-item label="审核状态">
                <el-select v-model="searchForm.approvalStatus" placeholder="全部" style="width:120px;">
                    <el-option label="全部" value="" />
                    <el-option label="待审核" value="待审核" />
                    <el-option label="通过" value="通过" />
                    <el-option label="不通过" value="不通过" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="init">查询</el-button>
                <el-button @click="handleReset">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 外出登记表 -->
        <el-table :data="tableData" v-loading="loading" border style="width:100%; margin-top:2%; background:#f5f7fa;"
            :header-cell-style="{ background: '#f9fafc', color: '#333', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }">
            <el-table-column label="客户姓名" min-width="9%">
                <template #default="scope">{{ scope.row.client.name || '-' }}</template>
            </el-table-column>
            <el-table-column label="性别" min-width="6%">
                <template #default="scope">{{ scope.row.client.gender || '-' }}</template>
            </el-table-column>
            <el-table-column label="联系电话" min-width="13%">
                <template #default="scope">{{ scope.row.client.phone || '-' }}</template>
            </el-table-column>
            <el-table-column label="外出原因" min-width="13%">
                <template #default="scope">{{ scope.row.leaveApply.reason || '-' }}</template>
            </el-table-column>
            <el-table-column label="外出时间" min-width="12%">
                <template #default="scope">{{ formatDate(scope.row.leaveApply.leaveTime) }}</template>
            </el-table-column>
            <el-table-column label="预计返回" min-width="12%">
                <template #default="scope">{{ formatDate(scope.row.leaveApply.expectedReturnTime) }}</template>
            </el-table-column>
            <el-table-column label="实际返回" min-width="12%">
                <template #default="scope">{{ formatDate(scope.row.leaveApply.actualReturnTime) }}</template>
            </el-table-column>
            <el-table-column label="办理人" min-width="8%">
                <template #default="scope">
                    <span class="user-link" @click="showUserDialog(scope.row.leaveApply.applyId)">
                        {{ getUserName(scope.row.leaveApply.applyId) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="审核状态" min-width="10%">
                <template #default="scope">
                    <el-tag v-if="scope.row.leaveApply.approvalStatus === '待审核'" type="warning">待审核</el-tag>
                    <el-tag v-else-if="scope.row.leaveApply.approvalStatus === '通过'" type="success">通过</el-tag>
                    <el-tag v-else type="danger">不通过</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="审批人" min-width="8%">
                <template #default="scope">
                    <span v-if="scope.row.leaveApply.approveId" class="user-link"
                        @click="showUserDialog(scope.row.leaveApply.approveId)">
                        {{ getUserName(scope.row.leaveApply.approveId) }}
                    </span>
                    <span v-else>-</span>
                </template>
            </el-table-column>
            <el-table-column label="审核时间" min-width="12%">
                <template #default="scope">{{ formatDate(scope.row.leaveApply.approvalTime) }}</template>
            </el-table-column>
            <el-table-column label="操作" min-width="13%">
                <template #default="scope">
                    <el-button v-if="scope.row.leaveApply.approvalStatus === '待审核'" type="primary" size="small"
                        @click="openAuditDialog(scope.row)">审核</el-button>
                    <el-button v-else size="small" disabled>已审</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-bar">
            <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.size"
                :total="pagination.total" :page-sizes="[5, 10, 20, 50]" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handlePageChange" />
        </div>
        <!-- 审核弹窗 -->
        <LeaveAuditDialog ref="auditDialogRef" @refresh="init" />

        <UserInfoDialog ref="userDialogRef" />
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, inject, provide } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import LeaveAuditDialog from '@/components/leave/LeaveAuditDialog.vue'
import UserInfoDialog from '@/components/UserInfoDialog.vue'
import qs from 'qs'

const axios = inject('axios')

const loading = ref(false)
const tableData = ref([])
const pagination = reactive({ page: 1, size: 10, total: 0 })
const searchForm = reactive({
    name: '',
    expectedReturnTime: '',
    approvalStatus: ''
})
const auditDialogRef = ref()

const userDict = ref({})
const getUserDict = async () => {
    try {
        const { data } = await axios.get('/user/listAll')
        userDict.value = {}
        data.data.forEach(u => { userDict.value[u.userId] = u })
    } catch (e) {
        userDict.value = {}
    }
}
provide('userDict', userDict) // 提供给子组件使用

const getUserName = userId => userDict.value[userId]?.username || '未知'
const userDialogRef = ref()
const showUserDialog = userId => {
    const userInfo = userDict.value[userId]
    if (userDialogRef.value && userInfo) userDialogRef.value.open(userInfo)
    else ElMessage.warning('无法找到用户信息')
}

const getQueryParams = () => ({
    name: searchForm.name,
    expectedReturnTime: searchForm.expectedReturnTime,
    approvalStatus: searchForm.approvalStatus,
    page: pagination.page,
    size: pagination.size
})

const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该外出记录？', '提示', { type: 'warning' })
        .then(async () => {
            try {
                const { data } = await axios.post('/leaveApply/deleteLogic',
                    qs.stringify({ applyId: row.leaveApply.applyId }),
                )
                if (data.status === 200) {
                    ElMessage.success('删除成功')
                    init()
                } else {
                    ElMessage.warning(data.msg || '删除失败')
                }
            } catch (e) {
                ElMessage.error('删除失败')
            }
        })
        .catch(() => { })
}

const formatDate = (str) => {
    if (!str) return '-'
    return str.split(' ')[0]
}

const init = async () => {
    getUserDict()
    loading.value = true
    try {
        const { data } = await axios.get('/leaveApply/page', { params: getQueryParams() })
        if (data.status === 200) {
            tableData.value = data.data || []
            pagination.total = data.total || 0
        } else {
            tableData.value = []
            pagination.total = 0
            ElMessage.warning(data.msg)
        }
    } catch (err) {
        tableData.value = []
        ElMessage.error('查询失败')
    } finally {
        loading.value = false
    }
}
const handlePageChange = (p) => { pagination.page = p; init() }
const handleSizeChange = (s) => { pagination.size = s; pagination.page = 1; init() }
const handleReset = () => {
    searchForm.name = ''
    searchForm.expectedReturnTime = ''
    searchForm.approvalStatus = ''
    pagination.page = 1
    init()
}
const openAuditDialog = (row) => { auditDialogRef.value.open(row) }

onMounted(() => {
    init()
})
</script>

<style scoped>
.user-link {
    color: #409EFF;
    cursor: pointer;
    text-decoration: underline;
}

.user-link:hover {
    color: #1872dd;
}
.page-root {
    width: 100%;
    min-height: 100%;
    box-sizing: border-box;
    background: #fff;
    padding: 0 3%;
}

.main-title {
    font-size: 1.7em;
    font-weight: bold;
    color: #333;
    margin-bottom: 2%;
    margin-top: 0%;
}

.search-bar {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    gap: 1.2em;
    margin-bottom: 1.5%;
}

.pagination-bar {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    margin-top: 2%;
    margin-bottom: 2%;
}
</style>
